// select32NumbersByS2.js

// 📦 号码池（01 ~ 49）
const allNumbers = Array.from({ length: 49 }, (_, i) =>
  (i + 1).toString().padStart(2, "0")
);

/**
 * 🎯 S2 策略：基于平均出号间隔回归选择号码
 * @param {Array} history 开奖历史窗口（每项包含 number）
 * @returns {Array} 选出的 32 个号码
 */
function select32NumbersByS2(history) {
  const windowSize = history.length;

  // 构建每个号码在窗口内出现的位置（相对位置）
  const numberIndexMap = {}; // 例如：{ '22': [1, 7, 11] }
  history.forEach((entry, i) => {
    const num = entry.number;
    if (!numberIndexMap[num]) numberIndexMap[num] = [];
    numberIndexMap[num].push(i);
  });

  // 计算每个号码的平均间隔和当前未出现间隔
  const scoreMap = {};
  allNumbers.forEach((num) => {
    const appearIndices = numberIndexMap[num] || [];

    if (appearIndices.length < 2) {
      scoreMap[num] = -Infinity; // 数据太少，跳过
      return;
    }

    // 计算出号间隔列表
    const intervals = [];
    for (let i = 1; i < appearIndices.length; i++) {
      intervals.push(appearIndices[i] - appearIndices[i - 1]);
    }

    const avgInterval = intervals.reduce((a, b) => a + b, 0) / intervals.length;
    const lastAppearIndex = appearIndices[appearIndices.length - 1];
    const notAppearSince = windowSize - 1 - lastAppearIndex;

    // 差值越小评分越高（间隔回归）
    const diff = Math.abs(notAppearSince - avgInterval);
    scoreMap[num] = 1 / (diff + 1e-6);
  });

  // 选出评分前 32 个号码
  return Object.entries(scoreMap)
    .sort((a, b) => b[1] - a[1])
    .map(([num]) => num)
    .slice(0, 32);
}

module.exports = select32NumbersByS2;
